﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace testProtobuf
{
    class SocketClient
    {
        public void runClient()
        {
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            int myPort = 8888;
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                //clientSocket.Blocking = false;
                //clientSocket.BeginConnect(new IPEndPoint(ip, myPort), new AsyncCallback(ConnectCallback), clientSocket);
                clientSocket.Connect(new IPEndPoint(ip, myPort));
                clientSocket.Blocking = false;
                String str = "buffer32332323";
                byte[] byteDateLine = System.Text.Encoding.ASCII.GetBytes(str);
                clientSocket.Send(byteDateLine, byteDateLine.Length, 0);

                string recvStr = "";
                byte[] recvBytes = new byte[1024];
                int bytes;
                bytes = clientSocket.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
                recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
                
                Console.WriteLine("server connection success");
            }
            catch (System.Exception e)
            {
                Console.WriteLine("server connection failed " + e.Message);
                return;
            } 
        }

        //private static void ConnectCallback(IAsyncResult ar)
        //{
        //    try
        //    {
        //        // Retrieve the socket from the state object.
        //        Socket client = (Socket)ar.AsyncState;

        //        // Complete the connection.
        //        client.EndConnect(ar);

        //        Console.WriteLine("Socket connected to {0}",
        //            client.RemoteEndPoint.ToString());
        //    }
        //    catch (Exception e)
        //    {
        //        Console.WriteLine(e.ToString());
        //    }
        //}
    }
}
